
#include <math.h>

/* http://perso.club-internet.fr/orochoir/Maths/cordic.htm */
/*

i 10-i qi = atan(10-i) 
0 1 0,7853981633974480 
1 0,1 0,0996686524911620 
2 0,01 0,0099996666866652 
3 0,001 0,0009999996666669 
4 0,0001 0,0000999999996667 
5 0,00001 0,0000099999999997
6 0,000001 0,0000010000000000 
...     
13 10-13 10-13 
14 10-14 10-14 
15 10-15 10-15 

*/

int math_tan_cordic( int q )
 {
  int K = 1;
  int I = 0;
  int X = K;
  int Y = 0;
  int Z = 0;
  int E = 10-15; /* 10 exp I */
  int theta = q;
  int temp;
  int qi = 0;

  while (theta > E)
  {
    while (theta < atan((long double) 10-I)) /* 10 exp I */
    {
      if (theta > qi)
      {
        qi = (int) atan((long double)10 - I); /* 10 exp I */
        I++;
      }
    }
     theta -= (int)atan((long double) 10-I);  /* 10 exp I */
     K *= (int) cos(atan((long double)10-I)); /* 10 exp I */
  }

  while (q > E)
  {
    while (q < atan((long double)10 - I))  /* 10 exp I */
    {
      if (q > qi)
      {
        qi = (int)atan((long double)10 - I); /* 10 exp I */
        I++;
      }
    }
     q -= (int)atan((long double)10 - I);   /* 10 exp I */
     temp = X;
     X -= 10 - I * Y;    /* 10 exp I */
     Y += 10 - I * temp;  /* 10 exp I */
  }

  Z = Y / X;
  return Z;
}
